﻿using Microsoft.AspNetCore.Http;
using System;
using System.Text;

namespace ServiceKit
{
    public class WebCache
    {
        private const string SessionName = "Firefly_Session";
        
        public static string Get(string key)
        {
            string SessionId = GetSessionId(GlobalHttpContext.Current);
            if (string.IsNullOrEmpty(SessionId))
                return GlobalHttpContext.Current.Session.GetString(key);
            return Cache.Get(SessionId + key);
        }

        public static bool Remove(string key)
        {
            string SessionId = GetSessionId(GlobalHttpContext.Current);
            if (string.IsNullOrEmpty(SessionId))
            {
                GlobalHttpContext.Current.Session.Remove(key);
                return true;
            }
            else
            {
                return Cache.Remove(SessionId + key);
            }
        }

        public static bool Set(string key, string value, int expireMinutes = 0)
        {
            return SetExpiry(key, value, 0);
        }

        public static bool SetExpiry(string key, string obj, int minutes)
        {
            string SessionId = GetSessionId(GlobalHttpContext.Current);
            if (string.IsNullOrEmpty(SessionId))
            {
                GlobalHttpContext.Current.Session.Set(key,Encoding.UTF8.GetBytes(obj));
                return true;
            }
            else
            {
                Cache.Remove(SessionId + key);
                return Cache.SetExpiry(SessionId + key,obj,minutes);//默认超时时间为2小时
            }
        }

        private static string GetSessionId(HttpContext context)
        {
            string SessionId = "";
            if (context == null) return SessionId;
            
            if (!context.Request.Cookies.ContainsKey(SessionName))
            {
                SessionId = Guid.NewGuid().ToString().Replace("-", "");
                context.Response.Cookies.Append(SessionName, SessionId);
            }
            else
            {
                SessionId = context.Request.Cookies[SessionName].ToString();
            }
            return SessionId;
        }
    }
}
